function handvec=plot_stdecomp(st,stdecomp,flag_mode,sample,stname,shocell) 
ch1=size(st); 
ch2=size(stdecomp); 
if ch1(2)~=1; error('ST must be a vector');end 
if ch2(1)~=ch1(1);error('Mismatch length ST and STDECOMP'); end 
tol=1e-5; 
if any( abs( sum(stdecomp,2)-st )  > tol )
    error('Could not recover smooth state from decomposition')
else
    disp('State recovered to tolerance level')
end
if length(sample)~=ch1(1);error('Mismatch SAMPLE and ST');end
if length(shocell)~=ch2(2);error('Mismatch SHOCELL and STDECOMP');end
switch flag_mode
    case 1
        disp('Stacked 1 Graph');
        barmode='stacked'; 
    case 2
        disp('Grouped 1 Graph')
        barmode='grouped'; 
    case 3
        barmode='stacked';
        disp('Stacked 2 Graphs')
    case 4
        disp('Grouped 2 Graphs')
        barmode='grouped'; 
end
if flag_mode > 2; 
    subpp=2; 
    cut=ceil(ch1(1)/2); 
    start =[1;cut+1]; 
    finish=[cut ch1(1)];     
else
    subpp=1; 
    start=1;finish=ch1(1); 
end 
figure;


handvec=zeros(2,1); 

for ii=1:subpp; 
    subplot(subpp,1,ii); 
    bar(sample(start(ii):finish(ii)),stdecomp((start(ii):finish(ii)),:),0.99,barmode); hold on;
    plot(sample(start(ii):finish(ii)),st(start(ii):finish(ii)),'--k','LineWidth',3);
    xlim([sample(start(ii))-0.25 sample(finish(ii))+0.25]);
    if ii==1
        title(['Decomposition of ',char(stname),' across shocks ',barmode],'FontSize',12);hold off;
    end
    if ii==subpp 
        handl=legend([shocell(:);{'St'}],'Location','BestOutside');
        set(handl,'FontSize',8); 
        legend boxoff
    end 
    hold off; 
end 
set(gcf,'PaperOrientation','Landscape');
set(gcf,'PaperPosition',[-.15  +0.35 11.25 8.15]);
handvec(1)=gcf; 

% Also provide the plot of all states vs. actual 
mat=zeros([ch2(1) 2 ch2(2)]); 
mat(:,2,:)=repmat(st,[1 1 ch2(2)]); 
mat(:,1,:)=reshape(stdecomp,[ch2(1) 1 ch2(2)]); 
in.xaxis=sample; 
in.pnames=shocell(:); 
in.width=[1.5 2.5]; 
in.style={'-b',':r'}; 
plotsaj(mat,1,in); 
handvec(2)=gcf; 
suptitle(['Decomposition of  ',char(stname),' one shock at a time']); 
set(gcf,'PaperOrientation','Landscape');
set(gcf,'PaperPosition',[-.15  +0.35 11.25 8.15]);

